package com.fzy.springsecurity2.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 
 * </p>
 *
 * @author fzy
 * @since 2024-10-07
 */

@Data
@TableName(value = "t_user", autoResultMap = true)
public class TUser extends Model<TUser> implements UserDetails {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField("name")
    private String name;

    @TableField("password")
    private String password;

    @TableField("email")
    private String email;

    @TableField("is_enabled")
    private Integer isEnabled;

    @TableField(value = "authorities", typeHandler = JacksonTypeHandler.class)
    private List<String> authorities;

    @Override
    public List<? extends GrantedAuthority> getAuthorities() {
        return ObjectUtils.isEmpty(authorities) ? List.of() : authorities.stream().map(SimpleGrantedAuthority::new).toList();
    }

    @Override
    public Serializable pkVal() {
        return this.id;
    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public boolean isAccountNonExpired() {
        return UserDetails.super.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return UserDetails.super.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return UserDetails.super.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return getIsEnabled() == 1;
    }
}
